import { Page } from '#/api.ts';
import { message } from 'antd';

export const fetchAllData = async <Entity, ApiParams>(
  params: ApiParams,
  api: (_params: ApiParams & Page) => Promise<{ data: Entity[]; total: number }>,
) => {
  const limit = 100;
  const page = 1;
  try {
    const { data: firstData, total } = await api({ ...params, page, limit, order: 'id DESC' });
    const restPage = Math.ceil(total / limit);

    const otherData = await Promise.all(
      Array.from({ length: restPage - 1 }, (_, i) =>
        api({ ...params, page: i + 2, limit, order: 'id DESC' }),
      ),
    );

    return [[...firstData, ...otherData.flatMap((i) => i.data)]];
  } catch (e) {
    message.error(e.message);
  }
};
